-- TopM
-- Create by chendh Jun/05/2015
-- 排行榜模块

module("TopM", package.seeall);

-- 配置表
local nationalityTable = {};
local nationalityList  = {};

local provinceTable = {};
local provinceList  = {};
local provinceIndexList = {};

-- 当前排行榜信息
local topType = 1;
local topData = {};
local mmTopData = {};
local activityTopData = {};
local topClearTime = -1;
local refreshInterval = 14 * 24 * 3600;
local whenChangeInfo;

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    nationalityTable = {};
    nationalityList  = {};
    nationIndexList  = {};

    provinceTable = {};
    provinceList  = {};
    provinceIndexList = {};

    -- 载入国籍配置表
    local nationality_CSV = get_nationality_CSV();
    for i = 1, #nationality_CSV do
        local id = nationality_CSV[i].id;

        -- 海外版本增加部分地区，香港、台湾之类的
        if not isOverseaPackage() then
            if nationality_CSV[i].for_oversea == 0 then
                nationalityTable[id] = nationality_CSV[i];
                table.insert(nationalityList, id);
                nationIndexList[nationality_CSV[i].index] = id;
            end
        else
            nationalityTable[id] = nationality_CSV[i];
            table.insert(nationalityList, id);
            nationIndexList[nationality_CSV[i].index] = id;
        end
    end

    -- 载入省简称配置表
    local province_CSV = get_province_CSV();
    for i = 1, #province_CSV do
        local id = province_CSV[i].id;
        provinceTable[id] = province_CSV[i];
        table.insert(provinceList, id);
        provinceIndexList[province_CSV[i].index] = id;
    end

    nationality_CSV = {};
    province_CSV    = {};
end

-- 模块初始化
function init()
    loadCsv();

    EventMgr.removeAll("TopM");

    -- 关注玩家更改信息的事件
    EventMgr.register("TopM", event.SET_RANK_BRIEF, function()
        whenChangeInfo();
    end);
end

-- 更改玩家信息
function whenChangeInfo()
    -- 把排行榜中的信息都更改
    for k, list in pairs(topData) do
        local topList = getTopData(k);
        if #topList > 0 then
            for key, value in pairs(topList) do
                if value.rid == rid then
                    value.name = ME.user.dbase:query("nickname");
                    value.nation_id = ME.user.dbase:query("nation_id");
                    break;
                end
            end
        end
    end
end

-- 获取排行榜版本号
function getVersion(id)
    local m = topData[id];

    if not m then
        return "";
    end

    return topData[id]["version"];
end

-- 获取活动排行榜版本号
function getActivityVersion(id)
    local m = activityTopData[id];

    if not m then
        return "";
    end

    return activityTopData[id]["version"];
end

-- 获取排行榜列表数据
function getTopData(id)
    local m = topData[id]

    if not m then
        return {};
    end

    return topData[id]["data"];
end

-- 获取活动排行榜列表数据
function getActivityTopData(id)
    local m = activityTopData[id]

    if not m then
        return {};
    end

    return activityTopData[id]["data"];
end

-- 获取大地图用排行榜列表数据
function getMainMapTopData(id)
    local m = mmTopData[id];

    if not m or #table.keys(m) < 1 then
        return {};
    end

    return mmTopData[id];
end

-- 获取大地图显示用排行榜列表国家
function getMainMapTopNation(id)
    -- 大地图用排行榜信息（上线时先下发的）
    local mmTopInfo = getMainMapTopData(id);

    -- 排行榜信息
    local topInfo = getTopData(id)[1];

    -- 玩家自己的分数信息
    local dungeonScoreInfo = ME.user.dbase:query("dungeon_score_info") or {};
    local meTopInfo = dungeonScoreInfo[id];

    if not mmTopInfo and not topInfo and not meTopInfo then
        -- 大地图用数据和排行榜数据都不存在
        return nil;
    end

    local topLayer, topScore = 0, 0;
    local mmTopLayer, mmTopScore = 0, 0;
    local meTopLayer, meTopScore, meTopCreateTime = 0, 0, 0;
    local finalTopLayer, finalTopScore, finalTopNation;

    if topInfo and topInfo.layer and topInfo.score then
        topLayer = topInfo.layer;
        topScore = topInfo.score;
    end

    if mmTopInfo and mmTopInfo.layer and mmTopInfo.score then
        mmTopLayer = mmTopInfo.layer;
        mmTopScore = mmTopInfo.score;
    end

    if meTopInfo and meTopInfo.layer and meTopInfo.score and meTopInfo.create_time then
        meTopLayer = meTopInfo.layer;
        meTopScore = meTopInfo.score;
        meTopCreateTime = meTopInfo.create_time;
    end

    local finalTopInfo = {};

    if topLayer > mmTopLayer or
       topLayer == mmTopLayer and topScore > mmTopScore then
        finalTopLayer = topLayer;
        finalTopScore = topScore;
        finalTopNation = topInfo.nation_id;
    else
        finalTopLayer = mmTopLayer;
        finalTopScore = mmTopScore;
        finalTopNation = mmTopInfo.nation_id;
    end

    -- 排行榜的最后一次刷新时间
    local lastRfreshTime = math.max(0, topClearTime - refreshInterval);
    if (meTopLayer >= finalTopLayer or
        meTopLayer == finalTopLayer and meTopScore >= finalTopScore) and
        lastRfreshTime < meTopCreateTime then
        -- 自己的记录是最新的，返回自己的国籍
        return ME.user.dbase:query("nation_id");
    else
        return finalTopNation;
    end
end

-- 检索国籍配置
function queryNationality(id, path)
    local tempTable;
    if topType == 2 then
        tempTable = provinceTable;
    else
        tempTable = nationalityTable;
    end
    if tempTable[id] == nil then
        -- 默认为冈布奥国~
        if path == nil or path == "" then
            return tempTable[0];
        else
            return tempTable[0][path];
        end
    end

    if path == nil or path == "" then
        return tempTable[id];
    end

    return tempTable[id][path];
end

-- 获取所有的国籍
function getNationalityList()
    -- 国内版
    if topeType == 2 then
        return provinceList;
    end

    return nationalityList;
end

-- 获取默认国籍
function getDefaultNationId()
    -- 冈布奥
    return 0;
end

-- IOS平台下判断是否已经同意开启排行榜
function agreeOpen()
    -- 不是IOS平台，直接同意
    if not isIosPlatform() then
        return true;
    end

    -- 是否已经确认同意
    if UserDefaultM.getStringForKey("is_agree_open_top")== "1" then
        return true;
    end

    return false;
end

-- 判断是否是首次进入排行榜
function isFirstVisitTop()
    local nickname = ME.user.dbase:query("nickname");
    if nickname == nil or nickname == "" then
        return true;
    end
    return false;
end

-- 更新排行榜信息
function update(id, list, version, clearTime)
    topData[id] = {};
    topData[id]["data"] = list;
    topData[id]["version"] = version;

    topClearTime = clearTime;

    EventMgr.fire(event.TOP_DATA_UPDATED);
end

-- 更新活动排行榜信息
function updateActivityTop(id, list, version)
    activityTopData[id] = {};
    activityTopData[id]["data"] = list;
    activityTopData[id]["version"] = version;

    EventMgr.fire(event.ACTIVITY_TOP_DATA_UPDATED);
end

-- 更新大地图用排行榜信息
function updateMainMapTopInfo(para)
    for id, args in pairs(para) do
        if mmTopData[id] == nil then
            mmTopData[id] = {};
        end

        mmTopData[id]["nation_id"] = args.nation_id;
        mmTopData[id]["layer"] = args.layer;
        mmTopData[id]["score"] = args.score;
        mmTopData[id]["rid"] = args.rid;
    end

    -- 抛出更新事件
    EventMgr.fire(event.NOTIFY_MAIN_MAP_TOP_INFO);
end

-- 获取下次重置时间
function getRemainingTime()
    local serverTime = TimeM.getServerTime();

    return topClearTime - serverTime;
end

-- 获取下次重置时间
function getActivityRemainingTime(activityId)
    local serverTime = TimeM.getServerTime();
    local closeTime = ActivityM.getRemainRunningTime(activityId);

    return closeTime - serverTime;
end


-- 修改国籍ID
function changeNation(rid, dungeonId, nationId)
    -- 修改国籍Id
    for k, list in pairs(topData) do
        local topList = getTopData(k);
        if #topList > 0 then
            for key, value in pairs(topList) do
                 if value.rid == rid then
                     value.nation_id = nationId;
                     break;
                 end
            end
        end
    end

    -- 修改mmtopdata 主地图信息
    local areas = table.keys(DungeonAreaM.getMainAreas());

    for _, id in pairs(areas) do
        local mmTopInfo = getMainMapTopData(id);
        if #table.keys(mmTopInfo) > 0 then
            if mmTopInfo.rid == rid then
                mmTopInfo.nation_id = nationId;
            end
        end
    end

    -- 抛出更新事件
    EventMgr.fire(event.NOTIFY_MAIN_MAP_TOP_INFO);
end

-- 获取国家名称对应的id (国内版本为省)
function getNationIdByIndex(index)
    local tempList;

    if topType == 2 then
        tempList = provinceIndexList;
    else
        tempList = nationIndexList;
    end

    if tempList[index] == nil then
        return 0;
    end

    return tempList[index];
end

-- 获取国家名称列表（排序后的）
function getNationIndexList()
    local tempList;

    if topType == 2 then
        tempList = provinceIndexList;
    else
        tempList = nationIndexList;
    end

    local indexList = table.keys(tempList);
    table.sort(indexList);
    return indexList;
end

-- 设置排行榜版本
function setTopType(flag)
    topType = flag;
end

function isInlandType()
    return topType == 2;
end
